package com.project.easy.common.framework.generator.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import com.project.easy.common.db.mybatisplus.core.util.PageConvertTool;
import com.project.easy.common.framework.generator.entity.FrameworkGeneratorProjectPackage;
import com.project.easy.common.framework.generator.mapper.FrameworkGeneratorProjectMapper;
import  com.project.easy.common.util.dto.PageResDto;
import  com.project.easy.common.util.exception.business.BusinessException;
import  com.project.easy.common.util.string.StringUtil;
import com.project.easy.common.framework.generator.entity.FrameworkGeneratorProject;
import com.project.easy.common.framework.generator.entity.dto.FrameworkGeneratorProjectExcuteDto;
import com.project.easy.common.framework.generator.entity.dto.GeneratorDto;
import com.project.easy.common.framework.generator.entity.dto.PageGeneratorDto;
import com.project.easy.common.framework.generator.service.IFrameworkGeneratorProjectPackageService;
import com.project.easy.common.framework.generator.service.IFrameworkGeneratorProjectService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author GreatorMan.cool
 * @since 2021-09-28
 */
@Service
@ConditionalOnClass(DataSourceConfig.class)
public class FrameworkGeneratorProjectServiceImpl extends ServiceImpl<FrameworkGeneratorProjectMapper, FrameworkGeneratorProject> implements IFrameworkGeneratorProjectService {

    @Autowired
    private DataSourceConfig dataSourceConfig;

    @Autowired
    private IFrameworkGeneratorProjectPackageService frameworkGeneratorProjectPackageService;
    /**
     * 分页查询
     *
     * @param param 参数
     * @return 分页数据
     */
    @Override
    public PageResDto<FrameworkGeneratorProject> pageList(PageGeneratorDto param) {
        Page<FrameworkGeneratorProject> page = new Page<>(param.getPageNum(), param.getPageSize());
        QueryWrapper<FrameworkGeneratorProject> queryWrapper = new QueryWrapper<>();
        if (StringUtil.isNotBlank(param.getProjectName())) {
            queryWrapper.like("project_name", param.getProjectName());
        }
        Page<FrameworkGeneratorProject> result  = this.baseMapper.selectPage(page, queryWrapper);
        return PageConvertTool.convert(result);
    }
    /**
     * 新增
     *
     * @param param 参数
     * @return 返回ID主键
     */
    @Override
    public Long add(GeneratorDto param) {
        FrameworkGeneratorProject frameworkGeneratorProject = new FrameworkGeneratorProject();
        BeanUtils.copyProperties(param, frameworkGeneratorProject);
        this.save(frameworkGeneratorProject);
        return frameworkGeneratorProject.getId();
    }

    /**
     * 修改
     *
     * @param param 参数管理
     * @return 返回 True 修改成功
     */
    @Override
    public Boolean update(GeneratorDto param) {
        if (Objects.isNull(param.getId())) {
            throw  new BusinessException("ID参数非法");
        }
        FrameworkGeneratorProject frameworkGeneratorProject = this.baseMapper.selectById(param.getId());
        if (Objects.isNull(frameworkGeneratorProject)) {
            throw  new BusinessException("ID非法!");
        }
        BeanUtils.copyProperties(param, frameworkGeneratorProject);
        this.baseMapper.updateById(frameworkGeneratorProject);
        return Boolean.TRUE;
    }
    /**
     * 生成代码
     * @param param 参数
     * @return true 成功
     */
    @Override
    public Boolean excute(FrameworkGeneratorProjectExcuteDto param) {

        FrameworkGeneratorProjectPackage frameworkGeneratorProjectPackage = this.frameworkGeneratorProjectPackageService.getBaseMapper().selectById(param.getProductPackageId());
        if (Objects.isNull(frameworkGeneratorProjectPackage)) {
            throw  new BusinessException("项目包ID非法");
        }
        FrameworkGeneratorProject frameworkGeneratorProject = this.baseMapper.selectById(frameworkGeneratorProjectPackage.getProjectId());
        if (Objects.isNull(frameworkGeneratorProject)) {
            throw  new BusinessException("项目ID非法");
        }
        // 代码生成器
        AutoGenerator mpg = new AutoGenerator();
        String projectPath = initConfig(mpg, frameworkGeneratorProject);
        // 包配置
        PackageConfig pc = new PackageConfig();
        pc.setModuleName(param.getModel());
        pc.setParent(frameworkGeneratorProjectPackage.getFullPackage());
        mpg.setPackageInfo(pc);
        // 自定义配置
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                // to do nothing
            }
        };
        // 如果模板引擎是 freemarker
        String templatePath = "/templates/mapper.xml.ftl";
        // 自定义输出配置
        List<FileOutConfig> focList = new ArrayList<>();
        // 自定义配置会被优先输出
        focList.add(new FileOutConfig(templatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输出文件名 ， 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化！！
                return projectPath + "/src/main/resources/mapper/" + pc.getModuleName()
                        + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
            }
        });
        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);
        // 配置模板
        TemplateConfig templateConfig = new TemplateConfig();
        templateConfig.setXml(null);
        mpg.setTemplate(templateConfig);
        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        strategy.setSuperEntityClass(frameworkGeneratorProject.getSuperEntityClass());
        strategy.setEntityLombokModel(true);
        strategy.setRestControllerStyle(true);
        // 写于父类中的公共字段
        strategy.setSuperEntityColumns("id");
        strategy.setInclude(param.getTables().split(","));
        strategy.setControllerMappingHyphenStyle(true);
        mpg.setStrategy(strategy);
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        mpg.execute();
        return Boolean.TRUE;
    }
    /**
     * 参数配置
     * @param mpg 参数
     * @param frameworkGeneratorProject  项目
     * @return 返回String
     */
    private  String initConfig(AutoGenerator mpg, FrameworkGeneratorProject frameworkGeneratorProject) {
        GlobalConfig gc = new GlobalConfig();
        String projectPath = frameworkGeneratorProject.getProjectPath();
        gc.setOutputDir(projectPath + "/src/main/java");
        gc.setAuthor(frameworkGeneratorProject.getAuthInfo());
        gc.setOpen(false);
        // gc.setSwagger2(true); 实体属性 Swagger2 注解
        mpg.setGlobalConfig(gc);
        mpg.setDataSource(dataSourceConfig);
        return projectPath;
    }
}
